/**
 * Created by tanbingqin on 2020/8/19.
 */
import {messages} from "share/common";
/**
 * 操作：申请额度按钮
 * 适用：行程卡片的差旅申请单
 */
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Form, Button, message, Modal, Row, Col, Switch, Select, Spin } from 'antd'
const Option = Select.Option;
import travelService from 'containers/request/travel-request/travel.service'
import requestService from 'containers/request/request.service'
import errorMessage from 'share/errorMessage';
import requestUtil from 'containers/request/slide/request-util'
import Condition from 'components/condition';
const If = Condition.If;
import ExpenseAmount from 'containers/request/new-request/expense-amount'
import Selector from 'components/selector'

class QuotaBtn extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      submitLoading: false,
      isShowModal: false,
      quotaObj: {},
    };
  }

  handleQuota = () => {
    //调接口查询amount
    const { info } = this.context;
    const { quotaObj } = this.props;
    this.setState({isShowModal: true, loading: true});
    requestService.getQuotaAmount(info.applicationOID).then(res => {
      let quotaObjTemp = JSON.parse(JSON.stringify(quotaObj));
      quotaObjTemp.quotaAmount = res.data.quotaAmount || 0;
      this.setState({quotaObj: quotaObjTemp, loading: false});
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  cancelSubmit = () => {
    this.setState({isShowModal: false});
  };

  getCompanyOID = () => {
    const { jobInfo, info } = this.context;
    let custForm = info.custFormValues || [];
    let resultCompanyOID = jobInfo.companyOID;
    custForm.forEach(item => {
      if (item.messageKey === 'select_company' && item.value) {
        resultCompanyOID = item.value;
      }
    });
    return resultCompanyOID;
  };

  handleStatusChange = (value, key) => {
    let { quotaObj } = this.state;
    if (key === 'quotaBankCardOID') {
      quotaObj.label = (value && value.paymentRemark) ? `${value.paymentRemark === '002' ? messages('request-1.key15')/*瑞贝卡*/ : messages('request-1.key16')/*领创A卡*/}(${value.bankAccountNo && value.bankAccountNo.substr(-4)})` : '';
      quotaObj[key] = value ? value.contactBankAccountOID : '';
      quotaObj.quotaBankCardDTO = value;
    } else {
      quotaObj[key] = value;
    }
    this.setState({quotaObj});
  };

  goSubmitQuota = () => {
    const { refreshInfo, info } = this.context;
    const { quotaObj } = this.state;
    if (quotaObj.takeQuota && !quotaObj.quotaBankCardOID) {
      message.error(messages('request-1.key267')/*请选择需要发放额度的账号*/);
      return;
    }
    //这里要实时保存单据
    let params = JSON.parse(JSON.stringify(info));
    params.takeQuota = quotaObj.takeQuota;
    params.quotaCurrencyCode = quotaObj.takeQuota ? quotaObj.quotaCurrencyCode : '';
    params.quotaAmount = quotaObj.quotaAmount;
    params.quotaBankCardOID = quotaObj.takeQuota ? quotaObj.quotaBankCardOID : '';
    this.setState({submitLoading: true});
    travelService.saveTravelRequest(params).then(res => {
      this.setState({submitLoading: false, isShowModal: false});
      message.success(messages('request-1.key251')/*已保存*/);
      refreshInfo();
    }).catch(err => {
      this.setState({submitLoading: false});
      message.error(messages('request-1.key252')/*操作失败:*/  + `${err.response.data.message}`);
    });
  };

  render() {
    const { loading, submitLoading, isShowModal, quotaObj } = this.state;
    const { info, form: formInfo } = this.context;
    return (
      <div className="request-btn">
        {requestUtil.isShowLimitLoanBtn(info, formInfo.customFormPropertyMap) && (
          <Button type="primary" onClick={this.handleQuota}>{messages('request-1.key13')/*申请额度*/}</Button>
        )}
        <Modal
          title={messages('request-1.key13')/*申请额度*/}
          visible={isShowModal}
          onCancel={this.cancelSubmit}
          width={'50%'}
          footer={[
            <Button key="back" onClick={this.cancelSubmit}>{messages('common.cancel')/*取消*/}</Button>,
            <Button
              key="submit"
              type="primary"
              loading={submitLoading}
              onClick={this.goSubmitQuota}
            >
              {messages('common.ok')/*确定*/}
            </Button>
          ]}
        >
          <div style={{height: 450}}>
            <Spin spinning={loading}>
              <Row type="flex" align="middle" style={{marginBottom: 12}}>
                <Col span={6}>
                  {messages('request-1.key810')/*额度开关*/}
                </Col>
                <Col span={16}>
                  <Switch
                    checked={quotaObj.takeQuota}
                    onChange={value => this.handleStatusChange(value, 'takeQuota')}
                  />
                </Col>
              </Row>
              <Row type="flex" align="top" style={{marginBottom: 12}}>
                <Col span={6} style={{lineHeight: '32px'}}>
                  {messages('request-1.key811')/*申请金额*/}
                </Col>
                <Col span={16}>
                  <ExpenseAmount
                    currencyList={[]}
                    value={{
                      currencyCode: quotaObj.quotaCurrencyCode,
                      amount: quotaObj.quotaAmount
                    }}
                    disabledCurrency
                    disabledAmount
                  />
                  <div style={{color: '#989898', marginTop: 4}}>{messages('request-1.key829')/*此额度由明细中个人支付且为人民币的金额计总*/}</div>
                </Col>
              </Row>
              <Row type="flex" align="middle">
                <Col span={6}>{messages('request-1.key14')/*额度发放至*/}</Col>
                <Col span={16}>
                  <Selector
                    placeholder={messages('request-1.key812')/*请选择账号*/}
                    type="quotaSupplierNoDynamic"
                    params={{
                      userOID: info.applicantOID,
                      companyOID: this.getCompanyOID()
                    }}
                    entity
                    value={quotaObj.quotaBankCardOID ? {label: quotaObj.label, key: quotaObj.quotaBankCardOID} : undefined}
                    onChange={e => this.handleStatusChange(e, 'quotaBankCardOID')}
                  />
                </Col>
              </Row>
            </Spin>
          </div>
        </Modal>
      </div>
    )
  }
}

QuotaBtn.propTypes = {
  quotaObj: React.PropTypes.object, //额度相关字段
};

QuotaBtn.contextTypes = {
  applicant: React.PropTypes.object,
  creditScore: React.PropTypes.object,
  jobInfo: React.PropTypes.object,
  form: React.PropTypes.object,
  info: React.PropTypes.object,
  close: React.PropTypes.func,
  refreshInfo: React.PropTypes.func,
  router: React.PropTypes.object,
  refreshQuotaObj: React.PropTypes.func,
};

function mapStateToProps(state) {
  return {}
}

export default connect(mapStateToProps)(QuotaBtn)
